package com.ncs.nc.controller;

import com.alibaba.fastjson.JSONObject;
import com.ncs.nc.entity.Goods;
import com.ncs.nc.entity.ResultObject;
import com.ncs.nc.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import java.awt.image.MultiPixelPackedSampleModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

@RestController
@RequestMapping("/goods")
public class GoodsController implements WebMvcConfigurer {

    private String resourceHandler="/upload/";//请求 url 中的资源映射，不推荐写死在代码中，最好提供可配置，如 /uploadFiles/**
    private String uploadFileLocation="D:/Projects/Project_IDEA/nc/src/main/resources/static/upload/";//上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值，如 E:/wmx/uploadFiles/

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/*").allowedOrigins("*");
    }

    @Autowired
    private GoodsService gs;
    @Autowired
    private ResultObject ro;

    //全查
    @RequestMapping("/all")
    @CrossOrigin(origins = "http://127.0.0.1:8848")
    public ResultObject all(){
        ro.setMsg("查询成功");
        ro.setStatus("200");
//        ro.setData(gs.list());
        ro.setData(gs.getAllGoods());
        return ro;
    }

    //单查
    @CrossOrigin(origins = "http://127.0.0.1:8848")
    @RequestMapping("/one/{cId}")
    public ResultObject getById(@PathVariable("GoodsId") Long GoodsId){
        ro.setMsg("查询成功");
        ro.setStatus("200");
        ro.setData(gs.getById(GoodsId));
        return ro;
    }

    //更新
    @CrossOrigin(origins = "http://127.0.0.1:8848")
    @RequestMapping("/update")
    public Object update(@RequestBody Goods Goods){
        ResultObject ro=new ResultObject<>();
        ro.setMsg("更新成功");
        ro.setStatus("200");
        ro.setData(gs.updateById(Goods));
        return ro;
    }

    //添加
    @CrossOrigin(origins = "http://127.0.0.1:8848")
    @RequestMapping("/add")
    public Object add(@RequestBody Goods goods){
        System.out.println(goods);
        ResultObject ro=new ResultObject<>();
        ro.setMsg("更新成功");
        ro.setStatus("200");
        ro.setData(gs.save(goods));
        return ro;
    }

    //删除
    @CrossOrigin(origins = "http://127.0.0.1:8848")
    @RequestMapping("/del/{cId}")
    public Object deleteById(@PathVariable("GoodsId") Long GoodsId){
        ResultObject ro=new ResultObject<>();
        ro.setMsg("删除成功");
        ro.setStatus("200");
        ro.setData(gs.removeById(GoodsId));
        return ro;
    }

    //条件查

    //分页查

    //排序

    //处理文件上传
    @RequestMapping("/upload")
    @CrossOrigin(origins = "http://127.0.0.1:8848")
    public ResultObject uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()) {
            ro.setMsg("");
            ro.setStatus("fail");
            return ro;
        }

//        String contentType = file.getContentType();
//        System.out.print(contentType);
//        String fileName = System.currentTimeMillis()+file.getOriginalFilename();
//        String filePath = "D:\\Projects\\Project_IDEA\\nc\\src\\main\\resources\\static\\upload";
////        String filePath = request.getSession().getServletContext().getRealPath("upload/");
//        System.out.println(filePath);
//        try {
//            uploadFile(file.getBytes(), filePath, fileName);
//            ro.setMsg(fileName);
//            ro.setStatus("success");
//            // ro.put("xfileName", filePath+"/"+fileName);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return ro;

        //basePath拼接完成后，形如：http://192.168.1.20:8080/fileServer
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        String fileName = file.getOriginalFilename();
        String fileServerPath = basePath + resourceHandler.substring(0, resourceHandler.lastIndexOf("/") + 1) + fileName;
        System.out.println("文件访问路径：" + fileServerPath);

        File saveFile = new File(uploadFileLocation, fileName);
        file.transferTo(saveFile);//文件保存

        System.out.println("文件保存路径：" + saveFile.getPath());
        ro.setMsg(fileServerPath);
        return ro;


    }

    //图片上传
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath +"/"+ fileName);
        out.write(file);
        out.flush();
        out.close();
    }

//    public DataJson image(MultipartFile file){
//        //调用工具类完成文件上传
//        String imagePath = UploadUtils.upload(file);
//        System.out.println(imagePath);
//        DataJson dataJson = new DataJson();
//        if (imagePath != null){
//            //创建一个HashMap用来存放图片路径
//            HashMap hashMap = new HashMap();
//            hashMap.put("src",imagePath);
//            dataJson.setCode(0);
//            dataJson.setMsg("上传成功");
//            dataJson.setData(hashMap);
//        }else{
//            dataJson.setCode(0);
//            dataJson.setMsg("上传失败");
//        }
//        return dataJson;
//    }


}
